package com.himiotech.core.project.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.model.SimpleDataTree;
import com.himiotech.core.framework.helper.model.XmSelectTree;
import com.himiotech.core.framework.helper.utils.ShiroUtils;
import com.himiotech.core.project.data.mapper.MenuMapper;
import com.himiotech.core.project.data.mapper.RoleMenuMapper;
import com.himiotech.core.project.helper.utils.TreeUtils;
import com.himiotech.core.project.model.entity.Menu;
import com.himiotech.core.project.model.entity.role.Role;
import com.himiotech.core.project.model.entity.user.User;
import com.himiotech.core.project.model.metadata.MenuMetadata;
import com.himiotech.core.project.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.*;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    public static final String PERMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     * 根据用户查询菜单
     *
     * @param user 用户信息
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectMenusByUser(User user) {
        List<Menu> menus;
        // 管理员显示所有菜单信息
        if (user.isAdmin()) {
            menus = menuMapper.selectMenuNormalAll();
        } else {
            menus = menuMapper.selectMenusByUserId(user.getUserId());
        }
        return TreeUtils.getChildPerms(menus, 0);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<Menu> selectMenuList(Menu menu) {
        List<Menu> menuList;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin()) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getSearchParams().put("userId", user.getUserId());
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<Menu> selectMenuAll() {
        List<Menu> menuList;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin()) {
            menuList = menuMapper.selectList(Wrappers.<Menu>query().orderByAsc(MenuMetadata.PARENT_ID.getColName(), MenuMetadata.ORDER_NUM.getColName()));
        } else {
            menuList = menuMapper.selectMenuAllByUserId(user.getUserId());
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StrUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<XmSelectTree> roleMenuTreeData(Role role) {
        Long roleId = role.getRoleId();
        List<XmSelectTree> xmSelectTrees;
        List<Menu> menuList = selectMenuAll();
        if (roleId != null) {
            List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
            xmSelectTrees = initXmSelectTree(menuList, roleMenuList, true);
        } else {
            xmSelectTrees = initXmSelectTree(menuList, null, true);
        }
        return xmSelectTrees;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<SimpleDataTree<Menu>> roleMenuSimpleTreeData(Role role) {
        Long roleId = role.getRoleId();
        List<SimpleDataTree<Menu>> simpleDataTreeList;
        List<Menu> menuList = selectMenuAll();
        if (ObjectUtil.isNotNull(roleId)) {
            List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
            simpleDataTreeList = initSimpleDataTree(menuList, roleMenuList, true);
        } else {
            simpleDataTreeList = initSimpleDataTree(menuList, null, true);
        }
        return simpleDataTreeList;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<XmSelectTree> menuTreeData() {
        List<Menu> menuList = selectMenuAll();
        return initXmSelectTree(menuList);
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<SimpleDataTree<Menu>> menuSimpleTreeData() {
        List<Menu> menuList = selectMenuAll();
        return initSimpleDataTree(menuList);
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll() {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<Menu> permissions = selectMenuAll();
        if (CollectionUtil.isNotEmpty(permissions)) {
            for (Menu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PERMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<XmSelectTree> initXmSelectTree(List<Menu> menuList) {
        return initXmSelectTree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<XmSelectTree> initXmSelectTree(List<Menu> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<XmSelectTree> xmSelectTrees = new ArrayList<>();
        boolean isCheck = roleMenuList != null;
        List<Tree<String>> menuXmSelectTree = TreeUtils.getMenuXmSelectTree(menuList, permsFlag);
        for (Tree<String> menu : menuXmSelectTree) {
            XmSelectTree tree = new XmSelectTree();
            tree.setValue(menu.getId());
            tree.setName(menu.getName().toString());
            if (isCheck) {
                tree.setSelected(roleMenuList.contains(menu.getId() + menu.get("perms")));
            }
            TreeUtils.addXmSelectTreeChildrenByParent(tree, menu, roleMenuList);
            xmSelectTrees.add(tree);
        }
        return xmSelectTrees;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<SimpleDataTree<Menu>> initSimpleDataTree(List<Menu> menuList) {
        return initSimpleDataTree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<SimpleDataTree<Menu>> initSimpleDataTree(List<Menu> menuList, List<String> roleMenuList, boolean permsFlag) {
        List<SimpleDataTree<Menu>> simpleDataTreeList = new ArrayList<>();
        boolean isCheck = ObjectUtil.isNotNull(roleMenuList);
        for (Menu menu : menuList) {
            SimpleDataTree<Menu> simpleDataTree = new SimpleDataTree<>();
            simpleDataTree.setId(menu.getMenuId());
            simpleDataTree.setPId(menu.getParentId());
            simpleDataTree.setName(transMenuName(menu, permsFlag));
            simpleDataTree.setTitle(menu.getMenuName());
            if (isCheck) {
                simpleDataTree.setChecked(roleMenuList.contains(menu.getMenuId() + menu.getPerms()));
                simpleDataTree.setSelected(simpleDataTree.isChecked());
            }
            simpleDataTree.setOriginObj(menu);
            simpleDataTreeList.add(simpleDataTree);
        }
        return simpleDataTreeList;
    }

    public String transMenuName(Menu menu, boolean permsFlag) {
        StringBuilder sb = new StringBuilder();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;").append(menu.getPerms()).append("</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public Menu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountMenuByParentId(Long parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRoleMenuByMenuId(Long menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }


    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(Menu menu) {
        long menuId = menu.getMenuId() == null ? -1L : menu.getMenuId();
        Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (ObjectUtil.isNotNull(info) && info.getMenuId() != menuId) {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }
}
